package com.ccx.library.handler.Aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccx.library.exception.AccessDeniedException;
import com.ccx.library.function.annotation.HasRole;
import com.ccx.library.module.parallel.service.UserRoleService;
import com.ccx.library.module.role.entity.Role;
import com.ccx.library.module.role.service.RoleService;
import com.ccx.library.util.HttpUtils;
import com.ccx.library.util.JwtProvide;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
@Slf4j
public class HasRoleHandler {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;
    @Pointcut("@annotation(com.ccx.library.function.annotation.HasRole)")
    public void HasRole(){}

    @Before("@annotation(HasRole)")
    public void doRole(JoinPoint joinPoint, HasRole HasRole) throws AccessDeniedException {
        HttpServletRequest request = HttpUtils.getRequest();
        String roleValue = HasRole.value();
        String token = request.getHeader("token");
        String username = (String) JwtProvide.getTokenClaim(token).get("username");
        /**
         * 通过username查询角色
         */
        Role role = userRoleService.QueryByUsername(username);
        Integer roleLevel = role.getRoleLevel();
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("role_level",roleLevel);
        List<Role> list = roleService.list(queryWrapper);
        List<String> roleList=new ArrayList<>();
        list.forEach(item->{
            roleList.add(item.getRoleCode());
        });
        if (!roleList.contains(roleValue)) {
            /**
             * 没有权限
             */
            throw new AccessDeniedException();
        }
    }
}
